#region Imported Namespaces
using System;
using System.Collections;
using System.Collections.Specialized;
using System.ComponentModel;
using System.ComponentModel.Design;
using System.Data;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.Design;
using System.Web.UI.WebControls;

using PHSRAG.Insight21.SearchContext;
using Calendar = PHSRAG.WebControls.Calendar;
using DataAccess = PHSRAG.Utility.DataAccess;
using SessionCachePolicy = PHSRAG.Insight21.Policy.SessionCachePolicy;
using Policy = PHSRAG.Insight21.Policy;
using UserContext = PHSRAG.Insight21.Context.UserContext;
using Constants = PHSRAG.Insight21.InsightUtilities.Constants;
#endregion

namespace PHSRAG.Insight21.InsightWebControls
{
	#region Class TransactionSearch
	/// <summary>
	/// The TransactionSearch control is used by Agreement summary pages.
	/// </summary>
	[ToolboxData("<{0}:TransactionSearch runat=server />"), Designer(typeof(TransactionSearchDesigner))]
	public class TransactionSearch : BaseSearch, INamingContainer, ISearch
	{
		#region Constants
		private const int	DefaultDate = -60;
		#endregion
		
		#region Instance Variables
		private Policy.ICachePolicy cachePolicy;
		private TextBox			accountNumber;
		private DropDownList	category;
		private TextBox			invoiceNumber;
		private TextBox			voucherNumber;
		private TextBox			journalNumber;
		private TextBox			requestorName;
		private TextBox			requisitionNumber;
		private DropDownList	transactionType;
		private Calendar		transactionTypeFrom;
		private Calendar		transactionTypeTo;
		private TextBox			enteredBy;
		private DropDownList	orderType;	
	
		/// <summary>
		/// Set default to and from dates, for puchasing data is by default retreived for last 60 days
		/// </summary>
		private string DefaultFromDate		=	DateTime.Now.AddDays(Utility.Settings.GetKeyValue("Purchasing.DefaultFromDate", DefaultDate)).ToShortDateString();
		private string DefaultToDate		=	DateTime.Now.ToShortDateString();
	

		#endregion

		#region ISearch Members
		/// <summary>
		/// Reset the internal search state. This involves setting the value for all controls to their default values
		/// and resetting the cached state of the search context.
		/// </summary>
		public void Reset()
		{
			ResetControls(Controls);

			transactionTypeFrom.Reset();
			transactionTypeTo.Reset();
			transactionTypeFrom.Prompt = DefaultFromDate;//CommonSearch.SelectPrompt;// "Select";
			transactionTypeTo.Prompt =  DefaultToDate;//CommonSearch.SelectPrompt;// "Select";

			TransactionSearchContext searchContext = cachePolicy.GetCachedObject(TransactionSearchContext.CacheKey) as TransactionSearchContext;
			if (searchContext != null)
				searchContext.Reset(Page.Request.Url.ToString());
		}

		/// <summary>
		/// Get the search criteria from the common search context.
		/// </summary>
		public SearchCriteria SearchCriteria
		{
			get
			{
				return ((TransactionSearchContext)cachePolicy.GetCachedObject(TransactionSearchContext.CacheKey)).GetSearchCriteria(Page.Request.Url.ToString());
			}
		}


		/// <summary>
		/// Get the search criteria. This is done by collecting the current values in all controls, storing them in the
		/// TransactionSearchContext, and then returning the search criteria.
		/// </summary>
		public SearchCriteria UpdateSearchCriteria()
		{
			UserContext userContext = (UserContext)cachePolicy.GetCachedObject(UserContext.CacheKey);
			return GetSearchCriteria(userContext.DomainUserId, Controls);
		}
		#endregion

		#region Protected Properties
		/// <summary>
		/// Determine if the control is in design mode. It is if there is not HTTP context.
		/// </summary>
		protected static bool IsDesignMode
		{
			get { return HttpContext.Current == null; }
		}
		#endregion

		#region Virtual Methods
		/// <summary>
		/// Invoked by the method which builds the HTML representation of the control tree. Derived classes would typically
		/// return the HTML to be inserted into the stream AFTER the indicated row.
		/// </summary>
		/// <param name="currentRowNumber">The number (starting from 1) of the row that the HTML returned by this method
		/// would be inserted at.
		/// </param>
		/// <returns>HTML string to add at row number currentRowNumber</returns>
		protected virtual string GetHTML(int currentRowNumber)
		{
			return string.Empty;
		}
		#endregion

		#region Overrides
		/// <summary>
		/// Create all controls. Notice that the creation is more than just instantiating the controls. It also involves
		/// in generating the underlying HTML so that the controls shows up per the need.
		/// </summary>
		protected override void CreateChildControls()
		{
			CreateControls();
			GenerateControlTree();
		}

		/// <summary>
		/// Initializes the cachepolicy. Create and cache a TransactionSearchContext object if necessary.
		/// Note that controls whose state must persist in the view state MUST be created BEFORE OnInit completes. We do
		/// this simply by invoking EnsureChildControls().
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnInit(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];
			TransactionSearchContext searchContext = cachePolicy.GetCachedObject(TransactionSearchContext.CacheKey) as TransactionSearchContext;
			if (searchContext == null)
			{
				searchContext = new TransactionSearchContext(cachePolicy);
				searchContext.Load(DataAccess.ConnectionString);
				searchContext.Cache();
			}

			EnsureChildControls();
			base.OnInit(e);
			searchContext.GetSearchCriteria(Page.Request.Url.ToString(), Controls);
		}


		/// <summary>
		/// Initialize the contents of all controls on first load. If the TransactionSearchContext is not cached yet, a
		/// new instance is created and cached.
		/// </summary>
		/// <param name="e">Argument associated with the event</param>
		protected override void OnLoad(EventArgs e)
		{
			cachePolicy = (Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey];

			if (!Page.IsPostBack)
			{
				EnsureChildControls();

				TransactionSearchContext searchContext = cachePolicy.GetCachedObject(TransactionSearchContext.CacheKey) as TransactionSearchContext;
				if (searchContext == null)
				{
                    searchContext = new TransactionSearchContext(cachePolicy);
					searchContext.Load(DataAccess.ConnectionString);
					searchContext.Cache();
				}

				LoadDropDownList(category, searchContext.Category, "ItemId");
				LoadDropDownList(orderType, searchContext.ALLTransactionTypes, "ItemId");
				LoadDropDownList(transactionType, searchContext.TransactionTypeValues, "ItemId");

				SetControlState(searchContext.GetSearchCriteria(Page.Request.Url.ToString()));
			}
		}
		#endregion

		#region Private Methods
		/// <summary>
		/// Create all controls in the CommonSearch.
		/// </summary>
		private void CreateControls()
		{
			Controls.Clear();

			accountNumber = new TextBox();
			accountNumber.ID = "accountNumber";
			accountNumber.CssClass = "DataInput";

			category = new DropDownList();
			category.ID = "category";
			category.CssClass = "DataInput";

			invoiceNumber = new TextBox();
			invoiceNumber.ID = "invoiceNumber";
			invoiceNumber.CssClass = "DataInput";

			journalNumber = new TextBox();
			journalNumber.ID = "journalNumber";
			journalNumber.CssClass = "DataInput";

			voucherNumber = new TextBox();
			voucherNumber.ID = "voucherNumber";
			voucherNumber.CssClass = "DataInput";

			requestorName = new TextBox();
			requestorName.ID = "requestorName";
			requestorName.CssClass = "DataInput";

			requisitionNumber = new TextBox();
			requisitionNumber.ID = "requisitionNumber";
			requisitionNumber.CssClass = "DataInput";

			transactionType = new DropDownList();
			transactionType.ID = "transactionType";
			transactionType.CssClass = "DataInput";

			enteredBy = new TextBox();
			enteredBy.ID = "enteredBy";
			enteredBy.CssClass = "DataInput";

			orderType = new DropDownList();
			orderType.ID = "orderType";
			orderType.CssClass = "DataInput";

			transactionTypeFrom = new Calendar();
			transactionTypeFrom.ID = "transactionTypeFrom";
			transactionTypeFrom.Prompt = DefaultFromDate;//CommonSearch.SelectPrompt;// "Select";

			transactionTypeTo = new Calendar();
			transactionTypeTo.ID = "transactionTypeTo";
			transactionTypeTo.Prompt =  DefaultToDate;//CommonSearch.SelectPrompt;// "Select";
		}

		/// <summary>
		/// Setup the control tree to reflect the actual (and exact) layout of the controls within the CommonSearch.
		/// </summary>
		private void GenerateControlTree()
		{
            string searchClientId = ((Policy.ICachePolicy)Page.Session[Policy.Names.CachePolicyKey]).GetCachedObject(Constants.SearchButtonClientIDKey) as string;
            if (searchClientId == null)
                searchClientId = "expandingPanel_commonSearch_search";

			Controls.Add(new LiteralControl(string.Format(
				"<table width=\"100%\" class=\"Search\" cellpadding=\"5\" cellspacing=\"5\" " +
                "onkeypress=\"return ClickButton(event, '{0}')\">\n",
                searchClientId)));
	
			Controls.Add(new LiteralControl(
				"\t<tr>" +
				"\t\t<td align=\"right\">Agreement Type: </td>" +
				"\t\t<td>"));
			Controls.Add(accountNumber);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>Category:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(category);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td>&nbsp;</td>" +
				"\t\t<td>\n\t\t\t" +
				"\t\t</td>" +
				"\t</tr>" +
				"\t<tr>" +
				"\t\t<td align='right'>Invoice&nbsp;#:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(invoiceNumber);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>Voucher&nbsp;#:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(voucherNumber);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>Journal&nbsp;#:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(journalNumber);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t</tr>" +
				"\t<tr>" +
				"\t\t<td align='right'>Requestor:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(requestorName);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>Requisition&nbsp;#:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(requisitionNumber);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>Type:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(orderType);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t</tr>" +
				"\t<tr>" +
				"\t\t<td align='right'>Transaction&nbsp;Type:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(transactionType);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>From:</td>" +
				"\t\t<td >\n\t\t\t"));

            Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)transactionTypeFrom);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td align='right'>To:</td>" +
				"\t\t<td>\n\t\t\t"));
            Controls.Add(IsDesignMode ? (Control)new LiteralControl(Calendar.DesignTimeHTML) : (Control)transactionTypeTo);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t</tr>" +
				"\t<tr>" +
				"\t\t<td align='right'>Entered&nbsp;By:</td>" +
				"\t\t<td>\n\t\t\t"));

			Controls.Add(enteredBy);

			Controls.Add(new LiteralControl(
				"\t\t</td>" +
				"\t\t<td>&nbsp;</td>" +
				"\t\t<td>&nbsp;</td>" +
				"\t\t<td>&nbsp;</td>" +
				"\t\t<td>&nbsp;</td>" +
				"\t</tr>" +
				"</table>"));			
		}
		#endregion

		#region Internal Methods
		/// <summary>
		/// This method is ONLY invoked by the associated designer to show the control contents at design time.
		/// </summary>
		internal void Design()
		{
			EnsureChildControls();
		}
		#endregion
	}
	#endregion

	#region Class PagerDesigner
	/// <summary>
	/// Designer associated with the TransactionSearch control.
	/// </summary>
	/// <remarks>
	/// This class cannot be used directly.
	/// </remarks>
	public class TransactionSearchDesigner : ControlDesigner
	{
		#region Overrides
		/// <summary>
		/// Force the control to create its child controls for display at design time.
		/// </summary>
		/// <returns>HTML representation of the control</returns>
		public override string GetDesignTimeHtml()
		{
			((TransactionSearch)Component).Design();
			return base.GetDesignTimeHtml();
		}
		#endregion
	}
	#endregion
}
// --- EOF ---